<?php

declare(strict_types=1);
// +----------------------------------------------------------------------
// | swiftAdmin 极速开发框架 [基于WebMan开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2030 http://www.swiftadmin.net
// +----------------------------------------------------------------------
// | swiftAdmin.net High Speed Development Framework
// +----------------------------------------------------------------------
// | Author: meystack <coolsec@foxmail.com> Apache 2.0 License
// +----------------------------------------------------------------------
namespace app\admin\controller\system;


use app\AdminController;
use app\common\library\Ip2Region;
use app\common\model\system\Porder as Porders;
use app\common\model\system\UserIntegralLog;
use support\Response;
use system\Random;
use think\facade\Db;

use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use Webman\Http\Request;
use think\Validate;


/**
 * 用户管理
 * Class User
 * @package app\admin\controller\system
 */
class Porder extends AdminController
{
    // 初始化函数
    public function __construct()
    {
        parent::__construct();
        $this->model = new Porders();
    }

    /**
     * 获取资源
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function index(): \support\Response
    {

        if (request()->isAjax()) {
            // 获取数据
            $post = \request()->all();
            $page = (int)input('page') ?? 1;
            $limit = (int)input('limit') ?? 10;
            // 生成查询条件
            $where = array();
            if (!empty($post['title'])) {
                $where[] = ['ordersn|name|mobile', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['status'])) {
                $where[] = ['status', 'in', $post['status']];
            }
            if (!empty($post['type'])) {
                $where[] = ['type', 'in', $post['type']];
            }
            $count = $this->model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $this->model->where($where)->order("id desc")->limit((int)$limit)->page((int)$page)->select();
            foreach ($list as $row) {
                $row['goodsinfo'] = json_decode($row['goodsinfo'], true) ?? [];
            }
            return $this->success('查询成功', "", $list, $count);
        }
        return view('/system/admin/porder', []);
    }

    /**
     * 修改显示状态
     */
    public function status()
    {
        if (request()->isAjax()) {
            $post = \request()->all();
            $validate = (new Validate())->rule([
                'id' => 'require',
                'status' => 'require|in:2,3,4',
            ]);
            $validate->message([
                'id.require' => 'ID不能为空',
                'status.require' => '状态不能为空',
                'status.in' => '状态类型错误'
            ]);
            if (!$validate->check($post)) {
                return $this->error($validate->getError());
            }
            $data = $this->model->find($post['id']);
            if (empty($data)) {
                return $this->error('订单不存在');
            }
            if ($data['status'] != 1 && $data['status'] != 2) {
                return $this->error('订单状态不可操作');
            }
            switch ($post['status']) {
                case '2':
                    Db::startTrans();
                    try {
                        $this->model->update($post);
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        return $this->error($e->getMessage());
                    }
                    return $this->success('操作成功！');
                    break;
                case '3':
                    Db::startTrans();
                    try {
                        $this->model->where('id', $post['id'])->update(['status' => $post['status']]);
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        return $this->error($e->getMessage());
                    }
                    return $this->success('操作成功！');
                    break;
                case '4':
                    Db::startTrans();
                    try {
                        $this->model->where('id', $post['id'])->update(['status' => $post['status']]);
                        if ($data['total'] > 0) {
                            UserIntegralLog::IntergralEdit($data['user_id'], $data['total'], 2, '积分兑换商品系统取消');
                        }
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        return $this->error($e->getMessage());
                    }
                    return $this->success('操作成功！');
                    break;
                default:
                    return $this->error('类型错误');
                    break;
            }
        }
        return $this->error();
    }
}
